//通过cavans转成图片数据，用于下载
var canvas = document.createElement('canvas');
var ctx = canvas.getContext('2d');

function draw(img) {
    console.log(img);
    var width = img.width, height = img.height;
    canvas.width = width;
    canvas.height = height;
    //清空画布
    ctx.clearRect(0, 0, width, height);
    //绘制图片到canvas
    ctx.drawImage(img, 0, 0);
}

//保存foreignObject形成的图片
var img = document.createElement('img');
var callback = function() {};
img.onload = function() {
    document.body.appendChild(img);
    draw(img);
    callback();
}

/**
 * 将dom节点的展示，利用foreignObject转换为图片
 * @param {DomObject} dom 要变为图片的dom
 */
function domToPic(dom) {
    if(!dom) {return};
    
    //克隆一个独立内存的节点
    var tempDom = dom.cloneNode(true);
    tempDom.setAttribute('xmlns', 'http://www.w3.org/1999/xhtml');
    tempDom.classList.remove('outline');
    
    var src = 'data:image/svg+xml;charset=utf-8,<svg xmlns="http://www.w3.org/2000/svg" width="'+ dom.offsetWidth +'" height="'+ dom.offsetHeight +'"><foreignObject x="0" y="0" width="100%" height="100%">'+ new XMLSerializer().serializeToString(tempDom).replace(/#/g, '%23').replace(/\n/g, '%0A') + document.querySelector('style').outerHTML +'</foreignObject></svg>';

    img.src = src;
}

//事件绑定与处理
var container = document.getElementById('container');
container.addEventListener('mouseover', function(e) {
    if(e.target !== this) {
        e.target.classList.add('outline');
    } else {
        this.classList.add('outline');
    }
});
container.addEventListener('mouseout', function(e) {
    if(e.target !== this) {
        e.target.classList.remove('outline');
    } else {
        this.classList.remove('outline');
    }
});
container.addEventListener('click', function(e) {
    domToPic(e.target);
    //构建下载链接
    var link = document.createElement('a');
    link.download = 'index_' + (new Date() + '').slice(1, 9) + '.png';
    link.style.display = 'none';
    callback = function() {
        link.href = canvas.toDataURL();
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
    }
})